<template>
  <div class="movie-list">
    <!-- 顶部统计卡片 -->
    <div class="stat-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <template #header>
              <div class="stat-header">
                <el-icon><Film /></el-icon>
                <span>电影总数</span>
              </div>
            </template>
            <div class="stat-value">{{ total }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <template #header>
              <div class="stat-header">
                <el-icon><Star /></el-icon>
                <span>平均评分</span>
              </div>
            </template>
            <div class="stat-value">{{ averageRating }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <template #header>
              <div class="stat-header">
                <el-icon><Calendar /></el-icon>
                <span>本月新增</span>
              </div>
            </template>
            <div class="stat-value">{{ monthlyNew }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <template #header>
              <div class="stat-header">
                <el-icon><View /></el-icon>
                <span>总浏览量</span>
              </div>
            </template>
            <div class="stat-value">{{ totalViews }}</div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <div class="left">
        <el-button type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>
          添加电影
        </el-button>
        <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
      <div class="right">
        <el-input
          v-model="searchQuery"
          placeholder="搜索电影..."
          class="search-input"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="filterGenre" placeholder="类型筛选" clearable @change="handleFilter">
          <el-option
            v-for="genre in genres"
            :key="genre"
            :label="genre"
            :value="genre"
          />
        </el-select>
        <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
          <el-option label="评分最高" value="rating" />
          <el-option label="最新上映" value="date" />
          <el-option label="最多浏览" value="views" />
        </el-select>
      </div>
    </div>

    <!-- 电影列表 -->
    <el-card class="movie-table-card" shadow="hover">
      <el-table
        :data="filteredMovies"
        style="width: 100%"
        v-loading="loading"
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="expand">
          <template #default="props">
            <div class="movie-detail">
              <el-descriptions :column="3" border>
                <el-descriptions-item label="简介">{{ props.row.summary }}</el-descriptions-item>
                <el-descriptions-item label="主演">{{ props.row.cast }}</el-descriptions-item>
                <el-descriptions-item label="类型">{{ props.row.genres }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="电影名称" min-width="200">
          <template #default="{ row }">
            <div class="movie-title">
              <span>{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="director" label="导演" min-width="120" />
        <el-table-column prop="releaseDate" label="上映日期" min-width="120" />
        <el-table-column prop="averageRating" label="评分" min-width="100" align="center">
          <template #default="{ row }">
            <div style="display: flex; justify-content: center; align-items: center; width: 100%;">
              <el-rate
                :model-value="row.averageRating / 2"
                :max="5"
                disabled
                show-score
                :score-template="`${row.averageRating}`"
                text-color="#ff9900"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="wishCount" label="浏览量" min-width="100">
          <template #default="{ row }">
            <span>{{ row.wishCount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(row)"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="handleView(row)"
              >
                <el-icon><View /></el-icon>
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑电影' : '添加电影'"
      width="60%"
      destroy-on-close
    >
      <movie-form
        v-if="dialogVisible"
        :movie="currentMovie"
        @submit="handleSubmit"
        @cancel="dialogVisible = false"
      />
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="电影详情"
      width="70%"
    >
      <div v-if="selectedMovie" class="movie-detail-dialog">
        <div class="movie-detail-header">
          <div class="detail-info">
            <h2>{{ selectedMovie.title }}</h2>
            <el-rate
              v-model="selectedMovie.averageRating"
              disabled
              show-score
              text-color="#ff9900"
            />
            <p class="detail-meta">
              <span>{{ selectedMovie.director }}</span>
              <span>{{ selectedMovie.releaseDate }}</span>
              <span>{{ selectedMovie.duration }}分钟</span>
            </p>
            <p class="detail-description">{{ selectedMovie.summary }}</p>
          </div>
        </div>
        <el-divider />
        <div class="detail-content">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="主演">{{ selectedMovie.cast }}</el-descriptions-item>
            <el-descriptions-item label="类型">{{ selectedMovie.genres }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Plus, 
  Edit, 
  Delete, 
  View, 
  Download,
  Film,
  Star,
  Calendar
} from '@element-plus/icons-vue'
import MovieForm from '@/components/MovieForm.vue'
import axios from 'axios'

const API_BASE = 'http://localhost:3001/api/movies'

const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)
const currentMovie = ref(null)
const selectedMovie = ref(null)
const filterGenre = ref('')
const sortBy = ref('')

// 模拟数据
const monthlyNew = ref(12)
const totalViews = ref(12345)
const genres = ['动作', '喜剧', '爱情', '科幻', '恐怖', '动画', '纪录片']

// 电影列表数据
const movies = ref([])

// 真实平均评分
const averageRating = computed(() => {
  if (!movies.value.length) return 0
  const sum = movies.value.reduce((acc, m) => acc + (Number(m.averageRating) || 0), 0)
  return (sum / movies.value.length).toFixed(1)
})

// 获取电影列表（从后端）
const fetchMovies = async () => {
  loading.value = true
  try {
    const res = await axios.get(API_BASE)
    movies.value = res.data
    total.value = res.data.length // 如有分页可改为res.data.total
  } catch (error) {
    ElMessage.error('获取电影列表失败')
  } finally {
    loading.value = false
  }
}

// 过滤后的电影列表
const filteredMovies = computed(() => {
  let list = movies.value
  if (searchQuery.value) {
    list = list.filter(movie =>
      movie.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      movie.director.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }
  if (filterGenre.value) {
    list = list.filter(movie => {
      if (!movie.genres) return false
      if (Array.isArray(movie.genres)) {
        return movie.genres.includes(filterGenre.value)
      }
      return movie.genres.split(',').map(g => g.trim()).includes(filterGenre.value)
    })
  }
  // 排序
  if (sortBy.value === 'rating') {
    list = [...list].sort((a, b) => (Number(b.averageRating) || 0) - (Number(a.averageRating) || 0))
  } else if (sortBy.value === 'date') {
    list = [...list].sort((a, b) => {
      // 兼容releaseDate为字符串或Date
      return new Date(b.releaseDate) - new Date(a.releaseDate)
    })
  } else if (sortBy.value === 'views') {
    list = [...list].sort((a, b) => (Number(b.wishCount) || 0) - (Number(a.wishCount) || 0))
  }
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return list.slice(start, end)
})

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1
}

// 处理排序（如需后端排序可调整）
const handleSort = () => {
  // 可根据sortBy.value排序
}

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  currentMovie.value = null
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (movie) => {
  isEdit.value = true
  currentMovie.value = { ...movie }
  dialogVisible.value = true
}

// 处理查看
const handleView = (movie) => {
  selectedMovie.value = movie
  viewDialogVisible.value = true
}

// 处理删除
const handleDelete = async (movie) => {
  try {
    await ElMessageBox.confirm('确定要删除这部电影吗？', '警告', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    await axios.delete(`${API_BASE}/${movie.id}`)
    ElMessage.success('删除成功')
    fetchMovies()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理导出
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 处理表单提交（添加/编辑）
const handleSubmit = async (movieData) => {
  try {
    if (isEdit.value) {
      await axios.put(`${API_BASE}/${movieData.id}`, movieData)
      ElMessage.success('更新成功')
    } else {
      await axios.post(API_BASE, movieData)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    fetchMovies()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 表格行样式
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return 'even-row'
  }
  return 'odd-row'
}

onMounted(() => {
  fetchMovies()
})
</script>

<style>
.movie-list {
  padding: 20px;
  max-width: 1800px;
  margin: 0 auto;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-header {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
}

.stat-header .el-icon {
  font-size: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-top: 10px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
}

.action-bar .left {
  display: flex;
  gap: 10px;
}

.action-bar .right {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.movie-table-card {
  margin-bottom: 20px;
}

.movie-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.movie-poster {
  width: 40px;
  height: 60px;
  border-radius: 4px;
  background: #f6f8fa;
  object-fit: cover;
}

.image-fallback {
  width: 40px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #bbb;
  font-size: 12px;
  background: #f6f8fa;
  border-radius: 4px;
}

.movie-detail {
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.movie-detail-dialog {
  padding: 20px;
}

.movie-detail-header {
  display: flex;
  gap: 20px;
}

.detail-poster {
  width: 200px;
  height: 300px;
  border-radius: 8px;
  background: #f6f8fa;
  object-fit: cover;
}

.detail-info {
  flex: 1;
}

.detail-info h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
}

.detail-meta {
  margin: 10px 0;
  color: #606266;
}

.detail-meta span {
  margin-right: 20px;
}

.detail-description {
  color: #606266;
  line-height: 1.6;
}

.detail-content {
  margin-top: 20px;
}

.even-row {
  background-color: #fafafa;
}

.odd-row {
  background-color: #ffffff;
}

.el-button-group .el-button {
  padding: 5px 12px;
}

.el-table__expand-icon {
  color: #409EFF;
}

.el-descriptions__label {
  width: 120px;
  color: #606266;
}

.el-descriptions__content {
  color: #303133;
}
</style> 